import datetime
import os
from pathlib import Path
import config_setting
import step_1_update_folder_last_modified

def get_folder_latest_mtime(folder_path):
    """
    递归获取文件夹的最新修改时间（包括所有子文件和子文件夹）

    Args:
        folder_path (Path): 文件夹路径

    Returns:
        datetime: 最新的修改时间
    """
    latest_time = 0
    folder_path = Path(folder_path)

    dir_mtime = os.path.getmtime(folder_path)
    latest_time = max(latest_time, dir_mtime)
    return datetime.datetime.fromtimestamp(latest_time) if latest_time > 0 else None
    # if deep_mode:
    #     try:
    #         # 遍历文件夹及其所有子目录
    #         for root, dirs, files in os.walk(folder_path):
    #             dirs[:] = [d for d in dirs if not any(fnmatch.fnmatch(d, pattern) for pattern in ignore_folder_list)]
    #             current_dir = Path(root)
    #
    #             # 检查当前目录的修改时间
    #             dir_mtime = os.path.getmtime(current_dir)
    #             latest_time = max(latest_time, dir_mtime)
    #
    #             # 检查当前目录下所有文件的修改时间
    #             for file in files:
    #                 file_path = current_dir / file
    #                 try:
    #                     file_mtime = os.path.getmtime(file_path)
    #                     latest_time = max(latest_time, file_mtime)
    #                 except OSError as e:
    #                     print(f"警告：无法获取文件 {file_path} 的修改时间: {e}")
    #                     continue
    #
    #         return datetime.datetime.fromtimestamp(latest_time) if latest_time > 0 else None
    #
    #     except Exception as e:
    #         print(f"错误：遍历文件夹时发生异常: {e}")
    #         return None
    # else:
    #     dir_mtime = os.path.getmtime(folder_path)
    #     latest_time = max(latest_time, dir_mtime)
    #     return datetime.datetime.fromtimestamp(latest_time) if latest_time > 0 else None


def get_zip_mtime(zip_file_path):
    """
    获取ZIP文件的修改时间

    Returns:
        datetime: ZIP文件的修改时间，如果文件不存在则返回None
    """
    zip_file_path = Path(zip_file_path)
    if not zip_file_path.exists():
        return None

    try:
        zip_mtime = os.path.getmtime(zip_file_path)
        return datetime.datetime.fromtimestamp(zip_mtime)
    except OSError as e:
        print(f"错误：无法获取ZIP文件修改时间: {e}")
        return None

def needs_repack(folder_path, file_path):
    """
    判断是否需要重新打包

    Returns:
        bool: True需要重新打包，False不需要
        tuple: (文件夹最新时间, ZIP文件时间) 用于调试信息
    """
    if config_setting.refresh_folder_modified:
        step_1_update_folder_last_modified.main(folder_path)

    # ignore_folder_list = config_setting.ignore_folder_list + ["node_modules, venv"]
    folder_time = get_folder_latest_mtime(folder_path)
    zip_time = get_zip_mtime(file_path)

    if folder_time is None:
        print("错误：无法获取文件夹时间信息")
        # return False, (None, None)
        return False

    # 如果ZIP文件不存在，肯定需要打包
    if zip_time is None:
        print(f"ZIP文件不存在，需要创建新的打包文件")
        # return True, (folder_time, None)
        return True

    # 比较时间戳
    needs_pack = folder_time > zip_time

    # if needs_pack:
    #     print(f"检测到文件夹有更新，需要重新打包")
    #     print(f"  文件夹最新修改: {folder_time}")
    #     print(f"  ZIP文件修改: {zip_time}")
    # else:
    #     print(f"文件夹无更新，跳过打包")
    #     print(f"  文件夹最新修改: {folder_time}")
    #     print(f"  ZIP文件修改: {zip_time}")

    # return needs_pack, (folder_time, zip_time)
    return needs_pack